//
//  DataFMDB.m
//  IOSDome
//
//  Created by clobe on 2019/4/15.
//  Copyright © 2019 clobe. All rights reserved.
//

#import "DataFMDB.h"

#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

@interface DataFMDB ()
{
    FMDatabase  *_db;
}
@end
static DataFMDB *_DBCtl = nil;
static NSString *const newDTimeTable = @"newDTimeTable"; //车辆提交表

@implementation DataFMDB

+ (instancetype)sharedDataBase{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_DBCtl == nil) {
            _DBCtl = [[DataFMDB alloc] init];
            [_DBCtl initDataBase];
        }
    });
    return _DBCtl;
}

- (id)copy{
    return self;
}

- (id)mutableCopy{
    return self;
}

- (id)copyWithZone:(NSZone *)zone{
    return self;
}

- (id)mutableCopyWithZone:(NSZone *)zone{
    return self;
}

-(void)initDataBase{
    // 实例化FMDataBase对象
    
    //设置数据库版本为1
    int dbVersion = 0;
    //判断本地有没有数据库文件
    if (![self isExistDB]) {
        //不存在 初始化数据库
        [self createDB];
    } else {
        //如果存在,那么获取版本信息
        [self createDB];
        NSString * currentVersion = [self getDBInfoValue];
        dbVersion = currentVersion.intValue;
    }
    
    switch (dbVersion) {   //判断版本信息
        case 0:
            [self createTables];
            [self setDBInfoValueWithString:@"1.0"];
            break;
        case 1:
             [self setDBInfoValueWithString:@"2.0"];
            break;
        default:
            
            break;
    }
    
    [_db close];
}


- (void)createTables {
    //数据库中创建表（可创建多张）
    NSString *newTimeModel = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id INTEGER PRIMARY KEY AUTOINCREMENT,userSN varchar(40),startTime varchar(40), endTime varchar(40));", newDTimeTable];
    BOOL result = [_db executeUpdate:newTimeModel];
    
    if (result) {
        NSLog(@"create table success");
    }
    
}


- (void)addUploadInfoModel:(id )model setEnumTable:(EnumdataTable )enumdata{
    [_db open];
    
    ///一定要使用缓存，时间复杂度减小10倍！
    [_db shouldCacheStatements];
    
    switch (enumdata) {
        case EnumDTime:
        {
            statisticalTimeEntity  *entity= (statisticalTimeEntity *)model;
            [_db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@ (id, userSN,startTime,endTime) VALUES (?,?,?,?)", newDTimeTable],entity.id, entity.userSN, entity.startTime, entity.endTime];
            break;
        }
        default:
            break;
    }
    [_db close];
}

/**
 修改仪表盘时间数据
 */
- (void)updateDateWithModel:(statisticalTimeEntity *)model{
    [_db open];
    BOOL result =  [_db executeUpdate:[NSString stringWithFormat:@"UPDATE '%@' SET userSN = ? ,startTime = ? ,endTime = ? WHERE id = ?", newDTimeTable], model.userSN ,model.startTime, model.endTime,@(model.id)];
    if (result) {
        NSLog(@"%@", [NSString stringWithFormat:@"update from '%@' success ", newDTimeTable]);
    }
    [_db close];
}

/**
 删除指定数据
 */
- (void)deleteUploadInfoModelWithStr:(EnumdataTable )enumdata setSearch:(NSString *)sel{
    [_db open];
    
    switch (enumdata) {
        case EnumDTime:
        {
            [_db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@ WHERE %@", newDTimeTable,sel]];
            break;
        }
        default:
            break;
    }
    [_db close];
}

/**
 删除指定表所有数据
 */
- (void)deleteTableAllData:(EnumdataTable )enumdata{
    [_db open];
    
    switch (enumdata) {
        case EnumDTime:
        {
            [_db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", newDTimeTable]];
            break;
        }
        default:
            break;
    }
    [_db close];
}
/**
 删除所有数据
 */
- (void)deleteTable{
    [_db open];
    
    BOOL result = [_db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", newDTimeTable]];
    if (result) {
        NSLog(@"%@", [NSString stringWithFormat:@"delete from '%@' success", newDTimeTable]);
    }

    [_db close];
}

/**
 获取搜索数据
 
 @return 搜索的所有数据
 */
- (NSMutableArray *)getAllSearchModels:(EnumdataTable )enumdata setSearch:(NSString *)sel{
    [_db open];
    NSMutableArray<id> *arr = [NSMutableArray array];
    switch (enumdata) {
        case EnumDTime:
        {
            FMResultSet *res = [_db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@", newDTimeTable,sel]];
            while ([res next]) {
                statisticalTimeEntity *model = [self buildingWithFMDB:res];
                [arr addObject:model];
            }
            break;
        }
       
        default:
            break;
    }
    
    [_db close];
    return arr;
}

/**
 获取所有数据
 
 @return 所有数据
 */
- (NSMutableArray *)getAllUploadInfoModels:(EnumdataTable )enumdata{
    [_db open];
    NSMutableArray<id> *arr = [NSMutableArray array];
    switch (enumdata) {
        case EnumDTime:
        {
            FMResultSet *res = [_db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@", newDTimeTable]];
            while ([res next]) {
                statisticalTimeEntity *model = [self buildingWithFMDB:res];
                [arr addObject:model];
            }
            break;
        }
        default:
            break;
    }
    
    [_db close];
    return arr;
}


-(statisticalTimeEntity *)getStatisticalinfo{
    [_db open];
    statisticalTimeEntity *item = nil;
    FMResultSet *res = [_db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ order by id desc limit 1", newDTimeTable]];
    while ([res next]) {
        item = [self buildingWithFMDB:res];
    }
    [_db close];
    return item;
}


#pragma mark - res转成模型  //楼宇表
- (statisticalTimeEntity *)buildingWithFMDB:(FMResultSet *)res {
    statisticalTimeEntity *model = [[statisticalTimeEntity alloc] init];
    model.id = [res intForColumn:@"id"];
    model.userSN = [res stringForColumn:@"userSN"];
    model.startTime = [res stringForColumn:@"startTime"];
    model.endTime = [res stringForColumn:@"endTime"];
    return model;
}


#pragma mark - 创建版本信息
- (BOOL)setDBInfoValueWithString:(NSString *)string
{
    if ([self getDBInfoValue]) {
        //更新版本
        [self updateVersionInfoWithString:string];
    }
    else
    {
        //插入版本
        [self insertVersionInfoWithString:string];
    }
    return YES;
}


#pragma mark - 更新版本号
-(BOOL)updateVersionInfoWithString:(NSString *)version {
    NSString *sql = @"UPDATE t_info SET version = ?";
    BOOL b = [_db executeUpdate:sql,version];
    return b;
}

#pragma mark - 插入版本号
-(BOOL)insertVersionInfoWithString:(NSString *)version
{
    NSString *sql = @"INSERT INTO t_info(version) VALUES(?)";
    BOOL b = [_db executeUpdate:sql,version];
    return b;
}

//判断是否存在数据库
-(BOOL)isExistDB {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:[self getDBPath]];
}

//得到路径
-(NSString *)getDBPath {
    // 获得Documents目录路径
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 文件路径
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"UploadInfo.sqlite"];
    return filePath;
}

//得到版本信息
- (NSString *)getDBInfoValue
{
    NSString *sql = @"select version from t_info";
    //注意   需要先打开数据库
    [_db open];
    FMResultSet *resultSet = [_db executeQuery:sql];
    
    NSString * version = nil;
    while ([resultSet next]) {
        version = [resultSet stringForColumn:@"version"];
    }
    return version;
}

#pragma mark - 初始化数据库
- (void)createDB {
    _db = [FMDatabase databaseWithPath:[self getDBPath]];
    [_db open];
    if (![_db open]) {
        NSLog(@"db open fail");
        return;
    }
}

@end
